package com.yayo.mangement.iface;

import com.alibaba.fastjson.JSONObject;
import com.yayo.mangement.authentication.context.ExportContext;
import org.springframework.util.StringUtils;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

/**
 * 导出xlsx必须实现的接口
 * @param <T> 导出表的列的实体类，列名使用注解@ColumnName
 * @param <C> 继承于ExportContext，要传的条件参数实体类，而前方传值时需要传递json串
 */
public interface XlsxExporter<T, C extends ExportContext> {

    public List<T> export(C context);

    default C getC(String contextJson){
        C c = null;
        if(!StringUtils.isEmpty(contextJson)){
            ParameterizedType pType = (ParameterizedType)this.getClass().getGenericInterfaces()[0];
            Type[] types = pType.getActualTypeArguments();
            try {
                C obj = (C) Class.forName(types[1].getTypeName()).newInstance();
                c = (C) JSONObject.parseObject(contextJson, obj.getClass());
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
        return c;
    }

    default T getT(){
        T t = null;
        ParameterizedType pType = (ParameterizedType)this.getClass().getGenericInterfaces()[0];
        Type[] types = pType.getActualTypeArguments();
        try {
            t = (T) Class.forName(types[0].getTypeName()).newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return t;
    }

}
